<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\index\controller;

use app\mini\model\Lawyer;
use think\Db;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Index extends Home
{
    public function index()
    {
        // 默认跳转模块
        if (config('home_default_module') != '' && config('home_default_module') != 'index') {
            $this->redirect(config('home_default_module') . '/index/index');
        }
        return '<style type="text/css">*{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ' . config("dolphin.product_name") . ' ' . config("dolphin.product_version") . '<br/><span style="font-size:30px">极速 · 极简 · 极致</span></p></div>';
    }

    public function import()
    {
        $inputFileName = 'uploads/files/lawyer.csv';
        // 打开文件
        if (($handle = fopen($inputFileName, 'r')) !== false) {
            // 逐行读取
            $count = 0;
            $isSave = false;
            while (($data = fgetcsv($handle, 1000, ',')) !== false) {
                // $data 是一个数组，包含了解析出来的字段
                if (count($data) < 7 || trim($data[1]) == 'name') continue;
                if (!$isSave && $data[1] !== '孔骏熙律师') {
                    continue;
                } else {
                    $isSave = true;
                }
//                print_r($data);
                if ($isSave) {
                    // 专业处理
                    $array = explode(' ', $data[2]);
                    $filteredArray = array_filter($array, function ($value) {
                        return $value !== null && $value !== '';
                    });
                    // 手机号处理
                    $phoneNumbers = $this->findPhoneNumbers($data[3]);
                    // 邮箱处理
                    $emails = $this->findEmail($data[4]);
                    // 执业证号
                    $number = '';
                    if (!empty($data[8]) && strstr($data[8], '执业证号：')) {
                        $number = str_replace('执业证号：', '', $data[8]);
                    }
                    // 地址解析
                    $addressResult = http_post('https://wangzc.wang/smAddress', ['address' => $data[6]]);
                    $addressArray = [];
                    if ($addressResult[0] == 200) {
                        $addressArray = $addressResult[1] ?? [];
                    }
                    $insertData = [
                        'avatar' => $data[0],
                        'name' => str_replace('律师', '', $data[1]),
                        'type' => implode(',', $filteredArray),
                        'mobile' => $phoneNumbers[0] ?? '',
                        'email' => $emails[0] ?? '',
                        'company' => $data[5],
                        'address' => $data[6],
                        'description' => $data[7],
                        'number' => $number,
                        'api_result' => json_encode($addressArray),
                        'area' => $addressArray['countyCode'] ?? $addressArray['cityCode'] ?? $addressArray['provinceCode'] ?? ''
                    ];
//                print_r($insertData);
                    Db::startTrans();
                    try {
                        (new Lawyer())->save($insertData);
                        Db::commit();
                        sleep(1);
                        $count++;
                    } catch (\Throwable $t) {
                        Db::rollback();
                    }
                }
            }
            // 关闭文件
            fclose($handle);
            echo "共计导入{$count}条数据";
        } else {
            echo "文件无法打开";
        }
    }

    public function findPhoneNumbers($text)
    {
        // 正则表达式匹配中国大陆手机号
        $pattern = '/1[3-9]\d{9}/';
        preg_match_all($pattern, $text, $matches);
        return $matches[0];
    }

    public function findEmail($text)
    {
        $pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/';
        preg_match_all($pattern, $text, $matches);
        return $matches[0];
    }
}
